package com.cff.mina.skt;
import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

import com.cff.util.Logger;

public class MsgRequestDecoder extends CumulativeProtocolDecoder {
	
	private Logger LOGGER = new Logger();
	private final int msgLength;
	
	public MsgRequestDecoder(int msgLength) {
		if(msgLength <= 0){
			throw new IllegalArgumentException("msgLength should be over 0.");
		}
		this.msgLength = msgLength;
	}

	public boolean doDecode(IoSession session, IoBuffer in,
			ProtocolDecoderOutput out) throws Exception {
		if (in.remaining() > msgLength) {
			in.mark();
			byte[] lenBytes = new byte[msgLength];
			in.get(lenBytes, 0, msgLength);
			int length = 0;
			try {
				length = this.getLength(lenBytes);

			} catch (NumberFormatException e) {
				session.close(true);
				return false;
			}
			if(in.remaining() < length){
				in.reset();
				return false;
			}
			byte[] bbIn = new byte[length];
			in.get(bbIn, 0, length);
			out.write(bbIn);
			return true;

		} else {
			return false;
		}
	}
	
	public int getLength(byte[] b) throws NumberFormatException {
		return Integer.parseInt(hexString(b),16);
	}
	
	/*
	 * 二行制转字符串
	 */
	private static String byte2hex(byte[] b) {

		StringBuffer hs = new StringBuffer();
		String stmp = "";
		for (int n = 0; n < b.length; n++) {
			stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
			if (stmp.length() == 1)
				hs.append("0").append(stmp);
			else
				hs.append(stmp);
		}
		return hs.toString().toUpperCase();
	}
	
	public static void main(String args[]){
		
	}
	
	public static String hexString(byte[] b) {
        StringBuffer d = new StringBuffer(b.length * 2);
        for (int i=0; i<b.length; i++) {
            char hi = Character.forDigit ((b[i] >> 4) & 0x0F, 16);
            System.out.println(hi);
            char lo = Character.forDigit (b[i] & 0x0F, 16);
            System.out.println(lo);
            d.append(Character.toUpperCase(hi));
            d.append(Character.toUpperCase(lo));
        }
        return d.toString();
    }
}
